package com.ruyiadmin.springboot.service.impls.system;

import com.alibaba.fastjson.JSON;
import com.ruyiadmin.springboot.common.beans.system.SystemCacheConfig;
import com.ruyiadmin.springboot.common.components.core.RuYiRedisComponent;
import com.ruyiadmin.springboot.common.components.core.RuYiSessionContext;
import com.ruyiadmin.springboot.common.core.system.entities.QueryResult;
import com.ruyiadmin.springboot.domain.dto.system.OrgUserTreeDTO;
import com.ruyiadmin.springboot.domain.dto.system.SysOrganizationDTO;
import com.ruyiadmin.springboot.domain.entity.system.SysOrganization;
import com.ruyiadmin.springboot.repository.system.ISysOrganizationRepository;
import com.ruyiadmin.springboot.service.iservices.system.ISysOrganizationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 机构表 服务实现类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysOrganizationServiceImpl extends ServiceImpl<ISysOrganizationRepository, SysOrganization>
        implements ISysOrganizationService {

    //region 实现类私有属性

    private final RuYiRedisComponent redisUtils;
    private final SystemCacheConfig systemCacheConfig;
    private final ISysOrganizationRepository orgRepository;
    private final RuYiSessionContext sessionContext;

    //endregion

    //region 加载组织机构缓存

    /**
     * 加载组织机构缓存
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void loadSysOrgCache() {
        List<SysOrganizationDTO> orgs = this.orgRepository.queryAllSysOrg();
        this.redisUtils.set(systemCacheConfig.getOrgCacheName(), JSON.toJSONString(orgs));
        log.info("RuYiAdmin sys orgs cache loaded");
    }

    //endregion

    //region 清理组织机构缓存

    /**
     * 清理组织机构缓存
     */
    @Override
    public void clearSysOrgCache() {
        this.redisUtils.del(systemCacheConfig.getOrgCacheName());
        log.info("RuYiAdmin sys orgs cache cleared");
    }

    //endregion

    //region 查询机构列表

    /**
     * 查询机构列表
     *
     * @return QueryResult
     * @throws Exception 异常
     */
    @Override
    public QueryResult<SysOrganizationDTO> getOrgTreeNodes() throws Exception {

        Object value = this.redisUtils.get(this.systemCacheConfig.getOrgCacheName());
        List<SysOrganizationDTO> orgs = JSON.parseArray(value.toString(), SysOrganizationDTO.class);

        //获取用户机构编号
        String orgId = this.sessionContext.getUserOrgId();
        SysOrganizationDTO root = orgs.stream().
                filter(t -> t.getId().equals(orgId)).
                collect(Collectors.toList()).
                get(0);


        this.initNodeChildren(root, orgs);

        QueryResult<SysOrganizationDTO> queryResult = new QueryResult<>();
        queryResult.setHttpStatusCode(HttpStatus.SC_OK);
        queryResult.setMessage("OK");
        queryResult.setTotalCount(0);
        List<SysOrganizationDTO> list = new ArrayList<>();
        list.add(root);
        queryResult.setList(list);

        return queryResult;
    }

    //endregion

    //region 获取机构、用户树

    /**
     * 获取机构、用户树
     *
     * @return QueryResult
     * @throws Exception 异常
     */
    @Override
    public QueryResult<OrgUserTreeDTO> getOrgUserTree() throws Exception {
        String orgId = this.sessionContext.getUserOrgId();
        OrgUserTreeDTO root = this.orgRepository.queryOrgTree(orgId).get(0);
        this.initOrgUserTreeChildren(root);
        List<OrgUserTreeDTO> list = new ArrayList<>();
        list.add(root);
        return QueryResult.success(list.size(), list);
    }

    //endregion

    //region 实现类私有方法

    //region 递归机构树

    /**
     * 递归机构树
     *
     * @param root 根节点
     * @param orgs 机构列表
     */
    private void initNodeChildren(SysOrganizationDTO root, List<SysOrganizationDTO> orgs) {
        List<SysOrganizationDTO> list = orgs.stream().
                filter(t -> t.getParentId() != null).
                filter(t -> t.getParentId().equals(root.getId())).
                collect(Collectors.toList());
        if (list.size() > 0) {
            root.setChildren(new ArrayList<>());
            root.getChildren().addAll(list.stream().
                    sorted(Comparator.comparing(SysOrganizationDTO::getSerialNumber)).
                    collect(Collectors.toList()));
            for (SysOrganizationDTO item : list) {
                this.initNodeChildren(item, orgs);
            }
        }
    }

    //endregion

    //region 递归机构、用户树

    /**
     * 递归机构、用户树
     *
     * @param root 根节点
     */
    private void initOrgUserTreeChildren(OrgUserTreeDTO root) {
        String orgId = root.getId();

        //加载用户
        List<OrgUserTreeDTO> orgUsers = this.orgRepository.queryUserTree(orgId);
        if (orgUsers.size() > 0) {
            root.setChildren(new ArrayList<>());
            root.getChildren().addAll(orgUsers.stream().
                    sorted(Comparator.comparing(OrgUserTreeDTO::getSerialNumber)).collect(Collectors.toList()));
        }

        //加载子机构
        List<OrgUserTreeDTO> subOrgs = this.orgRepository.queryOrgByParent(orgId);
        if (subOrgs.size() > 0) {
            if (root.getChildren() == null) {
                root.setChildren(new ArrayList<>());
            }
            root.getChildren().addAll(subOrgs.stream().
                    sorted(Comparator.comparing(OrgUserTreeDTO::getSerialNumber)).collect(Collectors.toList()));
        }

        subOrgs.forEach(this::initOrgUserTreeChildren);
    }

    //endregion

    //endregion

}
